//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.wsd.smartcarwasher.controller;

import com.wsd.smartcarwasher.configuration.GetSessionConfig;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.domain.Machine;
import com.wsd.smartcarwasher.domain.OrderPieStatistic;
import com.wsd.smartcarwasher.domain.Partner;
import com.wsd.smartcarwasher.service.*;
import com.wsd.smartcarwasher.util.DateUtil;
import com.wsd.smartcarwasher.util.ReturnUtil;
import com.wsd.smartcarwasher.util.TimeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(
        tags = {"统计相关接口"}
)
@Controller
@CrossOrigin
public class StatisticController {
    private static final Logger logger = LoggerFactory.getLogger(StatisticController.class);
    @Resource
    private StatisticService statisticService;
    @Resource
    private PartnerService partnerService;
    @Resource
    private WxService wxService;
    @Resource
    private MachineService machineService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private OfflineCountRecordService offlineCountRecordService;
    public StatisticController() {
    }

    @ApiOperation(
            value = "按照纬度查询订单统计信息",
            notes = "运营端-订单统计",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParam(
            name = "type",
            value = "查询的事件范围：天-day 周-week 月-month",
            required = true,
            dataType = "String"
    )
    @RequestMapping(
            value = {"/v1/query_turnover_trend"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap getOrderStatistics(@RequestParam("type") String type, HttpServletRequest request) {

        String sessionId = request.getHeader("authorization");

        String openId = this.wxService.getOpenId(sessionId);

        if (StringUtils.isBlank(openId)) {
            return ReturnUtil.Error(ResultState.LOGIN_AGAIN.getMsg());
        } else {
            Partner partner = this.partnerService.getPartnerByOpenId(openId);
            if (partner == null) {
                return ReturnUtil.Error(ResultState.NO_BIND_PARTNER.getMsg());
            } else {

                List<Machine> machines = this.machineService.getMachinesByPartnerId(partner.getId());
                if(partner.getIs_super()==1)
                {
                    machines=this.machineService.getAllMachine();
                }
                if(machines.size()==0){
                   return ReturnUtil.Success("暂无关联设备");
                }
                List<Integer> machineIds = (List)machines.parallelStream().map(Machine::getId).distinct().collect(Collectors.toList());

                return StringUtils.isBlank(type) ? ReturnUtil.Error(ResultState.QUERY_PARAM_IS_EMPTY.getMsg()) : ReturnUtil.Success(ResultState.QUERY_TURNOVER_TREND_SUCCESS.getMsg(), this.statisticService.queryTurnoverTrend(type, machineIds,partner.getId()));
            }
        }
    }

    @ApiOperation(
            value = "按照运营商名加门店的所有已消费订单",
            notes = "运营端-订单统计",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParams({@ApiImplicitParam(
            name = "pageNum",
            value = "页码，从1开始",
            required = false,
            dataType = "Integer"
    ), @ApiImplicitParam(
            name = "pageSize",
            value = "每页显示订单条数，默认为20",
            required = false,
            dataType = "Integer"
    )})
    @RequestMapping(
            value = {"/v1/order_of_machine"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap getOrderStatistics(@RequestParam("pageNum") int pageNum, @RequestParam(value = "pageSize",defaultValue = "20") int pageSize, HttpServletRequest request) {
String sessionId = request.getHeader("authorization");
        String openId = this.wxService.getOpenId(sessionId);
//String openId="o1MBY6MMA3D1NM_WuA8OuuwrgxrM";


        if (StringUtils.isBlank(openId)) {
            return ReturnUtil.Error(ResultState.LOGIN_AGAIN.getMsg());
        } else {
            Partner partner = this.partnerService.getPartnerByOpenId(openId);

            if (partner == null) {
                return ReturnUtil.Error(ResultState.NO_BIND_PARTNER.getMsg());
            } else {
                if(partner.getIs_dataer()==1)
                {
                    List<Machine> machines = this.machineService.getMachinesByPartnerId(partner.getMajor_account());

                    List<Integer> machineIds = (List)machines.parallelStream().map(Machine::getId).distinct().collect(Collectors.toList());

                    return ReturnUtil.Success(ResultState.QUERY_ORDER_STATISTICS_SUCCESS.getMsg(), this.statisticService.queryOrderInfoWithPaginationRu(machineIds, pageNum, pageSize,partner.getMajor_account()));
                }
                List<Machine> machines = this.machineService.getMachinesByPartnerId(partner.getId());
                List<Integer> machineIds = (List)machines.parallelStream().map(Machine::getId).distinct().collect(Collectors.toList());
                return ReturnUtil.Success(ResultState.QUERY_ORDER_STATISTICS_SUCCESS.getMsg(), this.statisticService.queryOrderInfoWithPaginationRu(machineIds, pageNum, pageSize,partner.getId()));
            }
        }
    }

    @ApiOperation(
            value = "按照不同纬度的饼图统计",
            notes = "运营端-订单统计",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParam(
            name = "type",
            value = "时段-timeQuantum，消费类型-serviceType，支付方式-payWay，车型-car 查询统计饼图",
            required = true,
            dataType = "String"
    )
    @RequestMapping(
            value = {"/v1/query_pie_chart"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap getOrderPieStatistics(@RequestParam("type") String type, HttpServletRequest request) {
String sessionId = request.getHeader("authorization");
        String openId = this.wxService.getOpenId(sessionId);
//String openId="o1MBY6MMA3D1NM_WuA8OuuwrgxrM";
        if (StringUtils.isBlank(openId)) {
            return ReturnUtil.Error(ResultState.LOGIN_AGAIN.getMsg());
        } else {
            Partner partner = this.partnerService.getPartnerByOpenId(openId);
            if (partner == null) {
                return ReturnUtil.Error(ResultState.NO_BIND_PARTNER.getMsg());
            } else {
                if(partner.getIs_dataer()==1)
                {
                    List<Machine> machines = this.machineService.getMachinesByPartnerId(partner.getMajor_account());
                    List<Integer> machineIds = (List)machines.parallelStream().map(Machine::getId).distinct().collect(Collectors.toList());
                    return ReturnUtil.Success(ResultState.QUERY_PIE_CHART_SUCCESS.getMsg(), this.statisticService.getStatisticInfo(machineIds, type,partner.getMajor_account()));
                }
                List<Machine> machines = this.machineService.getMachinesByPartnerId(partner.getId());
                List<Integer> machineIds = (List)machines.parallelStream().map(Machine::getId).distinct().collect(Collectors.toList());
                return ReturnUtil.Success(ResultState.QUERY_PIE_CHART_SUCCESS.getMsg(), this.statisticService.getStatisticInfo(machineIds, type,partner.getId()));
            }
        }
    }

    @ApiOperation(
            value = "登录成功后的主页统计",
            notes = "运营端-订单统计",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/machine_statistics"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap getMachinesStatistics(HttpServletRequest request) {
String sessionId = request.getHeader("authorization");
        String openId = this.wxService.getOpenId(sessionId);
//String openId="o1MBY6MMA3D1NM_WuA8OuuwrgxrM";
        if (StringUtils.isBlank(openId)) {
            return ReturnUtil.Error(ResultState.LOGIN_AGAIN.getMsg());
        } else {
            Partner partner = this.partnerService.getPartnerByOpenId(openId);
            if (partner == null) {
                return ReturnUtil.Error(ResultState.NO_BIND_PARTNER.getMsg());
            } else {
                if(partner.getIs_dataer()==1)
                {
                    Map<String, Object> result = new HashMap();
                    result.put("partner", this.partnerService.getPartnerById(partner.getMajor_account()));

                    result.put("statistic", this.statisticService.getStatistics(this.partnerService.getPartnerById(partner.getMajor_account())));

                    return ReturnUtil.Success(ResultState.QUERY_ORDER_STATISTICS_SUCCESS.getMsg(), result);
                }
                    Map<String, Object> result = new HashMap();
                    result.put("partner", partner);

                    result.put("statistic", this.statisticService.getStatistics(partner));

                return ReturnUtil.Success(ResultState.QUERY_ORDER_STATISTICS_SUCCESS.getMsg(), result);
            }
        }
    }





    @ApiOperation(
            value = "查询指定机器营业额统计信息",
            notes = "PC端-订单统计",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParam(
            name = "machineId",
            value = "机器id",
            dataType = "String"
    )
    @RequestMapping(
            value = {"/v1/turnover_statistics"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap statisticTurnover(@RequestParam(value = "machineId",required = false) String machineId,
                                      @RequestParam (value = "partnerId",required = false) Integer  partnerId,
                                      HttpServletRequest request) {
            String sessionId = request.getHeader("authorization");
        String openId = this.wxService.getOpenId(sessionId);
//String openId="o1MBY6MMA3D1NM_WuA8OuuwrgxrM";
//        String openId="o1MBY6MMA3D1NM_WuA8OuuwrgxrM";
        Partner partner = this.partnerService.getPartnerByOpenId(openId);

        if(partner.getIs_dataer()==1)
        {
            Map<String, Object> result = this.statisticService.getPcTurnoverStatistics(machineId,this.partnerService.getPartnerById(partnerId).getMajor_account());
            return ReturnUtil.Success(ResultState.QUERY_TURNOVER_STATISTICS_SUCCESS.getMsg(), result);
        }

        if(partnerId==null||partnerId==0)
        {
            partnerId=partner.getId();
        }
        Map<String, Object> result = this.statisticService.getPcTurnoverStatistics(machineId,partnerId);
        return ReturnUtil.Success(ResultState.QUERY_TURNOVER_STATISTICS_SUCCESS.getMsg(), result);
    }

    @ApiOperation(
            value = "pc端查询指定机器营业额和订单数趋势",
            notes = "PC端-订单统计",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParams({@ApiImplicitParam(
            name = "machineId",
            value = "机器id",
            dataType = "String"
    ), @ApiImplicitParam(
            name = "type",
            value = "查询的事件范围：天-day 周-week 月-month",
            required = true,
            dataType = "String"
    )})
    @RequestMapping(
            value = {"/v1/turnover_trend"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap turnoverTrend(@RequestParam(value = "machineId",required = false) String machineId,
                                  @RequestParam(value = "partnerId",required = false) Integer partnerId,
                                  @RequestParam("type") String type,HttpServletRequest request) {
String sessionId = request.getHeader("authorization");
        String openId = this.wxService.getOpenId(sessionId);
//String openId="o1MBY6MMA3D1NM_WuA8OuuwrgxrM";
//        String openId="o1MBY6I_3VGfA1wybkA7ZY8BcxHU";
        if (StringUtils.isBlank(openId)) {
//            Map<String, Object> result = this.statisticService.queryPcTurnoverTrend(machineId, type,partnerId);
//            return ReturnUtil.Success(ResultState.QUERY_TURNOVER_TREND_SUCCESS.getMsg(), result);
            return ReturnUtil.Error(ResultState.LOGIN_AGAIN.getMsg());
        } else {
            Partner partner = this.partnerService.getPartnerByOpenId(openId);
            if (partner == null) {
                Map<String, Object> result = this.statisticService.queryPcTurnoverTrend(machineId, type,partnerId);
                return ReturnUtil.Success(ResultState.QUERY_TURNOVER_TREND_SUCCESS.getMsg(), result);
            }else{
                if(partner.getIs_dataer()==1)
                {
                    Map<String, Object> result = this.statisticService.queryPcTurnoverTrend(machineId, type,partner.getMajor_account());
                    return ReturnUtil.Success(ResultState.QUERY_TURNOVER_TREND_SUCCESS.getMsg(), result);
                }
                Map<String, Object> result = this.statisticService.queryPcTurnoverTrend(machineId, type,partner.getId());
                return ReturnUtil.Success(ResultState.QUERY_TURNOVER_TREND_SUCCESS.getMsg(), result);
            }
        }

    }

    @ApiOperation(
            value = "pc端按照不同的统计方式统计订单数",
            notes = "PC端-订单统计",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParams({@ApiImplicitParam(
            name = "machineId",
            value = "机器id",
            dataType = "String"
    ), @ApiImplicitParam(
            name = "type",
            value = "时段-timeQuantum，消费类型-serviceType，支付方式-payWay，车型-car 查询统计饼图",
            required = true,
            dataType = "String"
    )})
    @RequestMapping(
            value = {"/v1/pie_chart"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap queryPieChart(@RequestParam(value = "machineId",required = false) String machineId,
                                  @RequestParam(value = "partnerId",required = false) Integer partnerId,
                                  @RequestParam("type") String type) {
        List<OrderPieStatistic> result = this.statisticService.getPcPieChart(machineId, type,partnerId);
        return ReturnUtil.Success(ResultState.QUERY_PIE_CHART_SUCCESS.getMsg(), result);
    }



    @ApiOperation(
            value = "pc端-登录成功后的主页统计",
            notes = "pc端-订单统计",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/order_statistics"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap getAllStatistics(HttpServletRequest request,
                                     @RequestParam(required = false)  Integer  machineId,
                                     @RequestParam (required = false) Integer  partnerId,
                                     @RequestParam(required = false)   String sTime,
                                     @RequestParam(required = false) String eTime
                                     ) {
        return statisticService.getAllStatistics(machineId,partnerId,sTime,eTime);
    }




    @ApiOperation(
            value = "pc端-顾客构成与交易贡献占比",
            notes = "顾客构成与交易贡献占比",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/order_poportion"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap getPoportion(HttpServletRequest request,
                                     @RequestParam(required = false)   String sTime,
                                     @RequestParam(required = false) String eTime
    ) {
        if(sTime==null&eTime==null)
        {
            sTime=TimeUtils.getFormatTime(new Date(),DateUtil.DATE_TIME_PATTERN);
            eTime=sTime;
        }
        return (ModelMap) statisticService.getPoportion(sTime,eTime);
    }







    @ApiOperation(
            value = "pc商家端-登录成功后的主页统计",
            notes = "pc商家端-订单统计",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/store/order_statistics"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap getStoreStatistics(HttpServletRequest request,
                                     @RequestParam(required = false)  Integer  machineId,
                                     @RequestParam (required = true) Integer  partnerId,
                                     @RequestParam(required = false)   String sTime,
                                     @RequestParam(required = false) String eTime
    ) {
        return statisticService.getAllStatistics(machineId,partnerId,sTime,eTime);
    }


    @ApiOperation(
            value = "pc端-登录成功后的主页统计-数据总览",
            notes = "pc端-数据总览",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/number_statistics"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap getAllNumberStatistics()
    {

        return statisticService.getAllNumberStatistics();
    }


    @ApiOperation(
            value = "pc-商家端-登录成功后的主页统计-数据总览",
            notes = "pc-商家端-数据总览",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/store/number_statistics"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap getStoreNumberStatistics()
    {
        GetSessionConfig config=new GetSessionConfig();

        Map<String,String> map= config.getStorePartnerId("查看主页统计",request);
        if(map==null)
        {
            return  ReturnUtil.Error(null);
        }
        int partnerId=Integer.parseInt(map.get("partnerId"));
        return statisticService.getStoreNumberStatistics(partnerId);
    }

    @ApiOperation(
            value = "pc端-登录成功后的主页统计-top10",
            notes = "pc端-数据总览",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/order_top10"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap getAllOrderTop10()
    {
        return statisticService.getAllOrderTop10();
    }


    @ApiOperation(
            value = "【new】-日期或时间段的交易金额、交易笔数、顾客数的数据",
            notes = "pc端-数据概览",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/order_dataview"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap getOrderDataView(@RequestParam(required = false)String sTime,
                                     @RequestParam(required = false)String eTime,
                                     @RequestParam(required = false,defaultValue = "0")int partnerId
                                     )
    {
        if(sTime==null&&eTime==null)
        {
            sTime=TimeUtils.getFormatTime(new Date(),DateUtil.DATE_TIME_PATTERN);
            eTime=sTime;
        }

        return statisticService.getAllDataView(sTime,eTime,partnerId);
    }



    @ApiOperation(
            value = "【new】-一天内间隔两个小时的交易金额、交易笔数、顾客数的数据",
            notes = "pc端-数据统计",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/time/order_dataview"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap getOrderTimeView(@RequestParam(required = false)String sTime,
                                     @RequestParam(required = false,defaultValue = "0")int partnerId)
    {
        if(sTime==null)
        {
            sTime=TimeUtils.getFormatTime(new Date(),DateUtil.DATE_TIME_PATTERN);
        }
        return ReturnUtil.Success("查询成功",statisticService.getTimeDataView(sTime,partnerId));
    }


    @ApiOperation(
            value = "【new】-一周内交易金额、交易笔数、顾客数的数据",
            notes = "pc端-数据统计",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/week/order_dataview"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap getOrderWeekView(@RequestParam(required = false)String sTime,@RequestParam(required = false) String eTime,@RequestParam(required = false,defaultValue = "0") int partnerId)
    {

        if(sTime==null)
        {
            sTime=TimeUtils.getFormatTime(new Date(),DateUtil.DATE_TIME_PATTERN);
            eTime=TimeUtils.getFormatTime(new Date(),DateUtil.DATE_TIME_PATTERN);
        }
        return ReturnUtil.Success("查询成功",statisticService.getWeekDataView(sTime,partnerId));
    }

//    @ApiOperation(
//            value = "【new】-查询线下洗车订单数",
//            notes = "pc端-查询线下洗车订单数",
//            produces = "application/json",
//            response = ModelMap.class
//    )
//    @RequestMapping(
//            value = {"/v1/offline/count"},
//            method = {RequestMethod.GET},
//            produces = {"application/json; charset=utf-8"}
//    )
//    @ResponseBody
//    public ModelMap getOrderWeekView(@RequestParam(required = false)String sTime,@RequestParam(required = false) Integer partnerId)
//    {
//
//        return ReturnUtil.Success("查询成功",this.offlineCountRecordService.getOfflineCountRecord(sTime,partnerId));
//    }



    @ApiOperation(
            value = "【new】指定天数内的新老顾客数量",
            notes = "pc端-数据统计",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/month/customer_dataview"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap getOrderMonthView(@RequestParam(required = false) String sTime,
                                      @RequestParam(required = false,defaultValue = "0") Integer partnerId,
                                      @RequestParam(required = false,defaultValue = "30") Integer day
                                      )
    {
        if(sTime==null)
        {
            sTime=TimeUtils.getFormatTime(new Date(),DateUtil.DATE_TIME_PATTERN);
        }
        return ReturnUtil.Success("查询成功",statisticService.getMonthDataView(partnerId,DateUtil.convertStringToDate(sTime),day));
    }

    @ApiOperation(
            value = "【new】所选日期或时间段顾客的增长量",
            notes = "pc端-数据统计",
            produces = "application/json",
            response = ModelMap.class
    )
    @RequestMapping(
            value = {"/v1/day/customer_dataview"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap getOrderDayView(@RequestParam(required = false,defaultValue = "0")Integer partnerId,
                                    @RequestParam(required = false)String sTime,
                                    @RequestParam(required = false)String eTime
                                   )
    {
        if(sTime==null&eTime==null)
        {
            sTime=TimeUtils.getFormatTime(new Date(),DateUtil.DATE_TIME_PATTERN);
            eTime=sTime;
        }

        return ReturnUtil.Success("查询成功",statisticService.getDayDataView(partnerId,sTime,eTime));
    }

}
